﻿#include "XApplication.h"
#include"kits/Tools.h"
#include"QBreakpadHandler.h"
#include<QMutex>
#include<QMutexLocker>
#include<QFile>
#include<QDateTime>
#include<QTextStream>
#include<Windows.h>


static void MessageOutPut(QtMsgType type,const QMessageLogContext& context,const QString& msg)
{
   Q_UNUSED(type)
   Q_UNUSED(context)
   static bool _printInfo = deBugOpen();
   static QMutex mutex;
   QMutexLocker locker(&mutex);
   fprintf(stderr,"%s\n",msg.toLocal8Bit().data());
   if(!_printInfo) return;
   QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
   QString message = QString("%1 %2").arg(current_date_time).arg(msg);
   QFile file(LOG_FILE);
   file.open(QIODevice::WriteOnly | QIODevice::Append);
   QTextStream text_stream(&file);
   text_stream << message << "\r\n";
   file.flush();
   file.close();
}


XApplication::XApplication(const char* appName,int &argc, char **argv):QApplication(argc,argv)
{

#ifdef QT_NO_DEBUG
    QBreakpadInstance.setDumpPath("crashs");
#endif
    checkOnly(appName);
    qInstallMessageHandler(MessageOutPut);

    setApplicationName("XZPCode");
    setApplicationVersion("1.0.0.1");
    setOrganizationName("new thinging studio.std");
    setOrganizationDomain("www.baidu.org");
}

XApplication::~XApplication()
{
    xPrint;
}

void XApplication::checkOnly(const char* appName)
{
    if(multOpen()) return;
    //  创建互斥量
    HANDLE m_hMutex  = CreateMutex(NULL, FALSE, LPCWSTR(appName));
    //  检查错误代码
    if  (GetLastError() == ERROR_ALREADY_EXISTS)  {
      //  如果已有互斥量存在则释放句柄并复位互斥量
     CloseHandle(m_hMutex);
     m_hMutex  =  NULL;
      //  程序退出
      exit(0);
    }

}



